<template>
  <view class="ng-image">
    <image
      v-bind="$attrs"
      ref="imageRef"
      :class="'ng-image_main'"
      :src="showSrc"
      @error="handleError"
    />
  </view>
</template>

<script lang="ts" setup>
import { getCurrentInstance, nextTick, onMounted, onUnmounted, ref } from 'vue';

const props = defineProps<{
  dataSrc: string;
}>();

const showSrc = ref('');
// 当前重试次数
const retryCount = ref(0);
// 最大重试次数
const maxRetryCount = ref(5);

const imageRef = ref(null) as any;

const instance = ref(null) as any;
const observer = ref(null) as any;

const handleError = (e) => {
  // 每次重试前，先将showSrc重置为空，避免显示之前的图片
  showSrc.value = '';

  if (retryCount.value < maxRetryCount.value) {
    // 如果还没有达到最大重试次数，则继续重试
    retryCount.value++;
    console.log('====================================');
    console.log('重试次数：', retryCount.value);
    console.log('====================================');
    nextTick(() => {
      showSrc.value = props.dataSrc;
    });
  } else {
    // 如果已经达到最大重试次数，则显示默认图片
    showSrc.value = props.dataSrc;
  }
};

onMounted(() => {
  instance.value = getCurrentInstance();
  observer.value = uni.createIntersectionObserver(instance.value);
  observer.value.relativeToViewport().observe('.ng-image_main', (res) => {
    if (res.intersectionRatio > 0) {
      showSrc.value = props.dataSrc;
      observer.value.disconnect();
    }
  });
});

onUnmounted(() => {
  observer.value.disconnect();
});
</script>
